package com.example.service.webhook.business.taobao.service;

import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import com.example.service.webhook.business.email.entity.EmailBillShoppingSheetEntity;
import com.example.service.webhook.business.fund.dto.FundDetails;
import com.example.service.webhook.business.taobao.api.TaobaoClient;
import com.example.service.webhook.business.taobao.billitem.TaobaoTask;
import com.example.service.webhook.business.taobao.dto.DeliverAddress;
import com.example.service.webhook.business.taobao.dto.RecentDeliverAddress;
import com.example.service.webhook.business.taobao.dto.TaobaoSubOrder;
import com.example.service.webhook.business.taobao.dto.TaobaoUserInfo;
import com.example.service.webhook.business.taobao.dto.TradeDetails;
import com.example.service.webhook.business.taobao.dto.TradeDetailsRes;
import com.example.service.webhook.business.taobao.entity.DeliverAddressEntity;
import com.example.service.webhook.business.taobao.entity.RecentAddressEntity;
import com.example.service.webhook.business.taobao.entity.SubOrderEntity;
import com.example.service.webhook.business.taobao.entity.TradeDetailEntity;
import com.example.service.webhook.business.taobao.entity.UserInfoEntity;
import com.example.service.webhook.business.taobao.repository.RecentAddressRepository;
import com.example.service.webhook.business.taobao.repository.TaobaoDeliverAddressRepository;
import com.example.service.webhook.business.taobao.repository.TaobaoSuborderRepository;
import com.example.service.webhook.business.taobao.repository.TaobaoTradeInfoRepository;
import com.example.service.webhook.business.taobao.repository.UserInfoRepository;
/**
 * taobao处理类
 * userId+mappingId做为一个基础对象，mappingId是魔蝎为淘宝账号生成的一个id，一个淘宝账号的id不会变
 * ClassName: TaobaoService    
 * date: 2016年7月20日 下午5:35:35   
 * @author yuandong  
 * @version   
 * @since JDK 1.6
 */
@Service
public class TaobaoService {
	private static final Logger LOGGER = LoggerFactory.getLogger(TaobaoService.class);

	@Autowired
	private ThreadPoolTaskExecutor taskExecutor;
	@Autowired
	private TaobaoClient taobaoClient;
	@Autowired
	private UserInfoRepository userInfoRepository;
	@Autowired
	private TaobaoDeliverAddressRepository taobaoDeliverAddressRepository;
	@Autowired
	private RecentAddressRepository recentAddressRepository;
	@Autowired
	private TaobaoTradeInfoRepository taobaoTradeInfoRepository;
	@Autowired
	private TaobaoSuborderRepository taobaoSuborderRepository;
	
	


	/**
	 * 
	 * fetchBill:处理邮箱下面的所有账单 <br/>
	 * 在收到魔蝎的邮箱账单回调时执行<br/>
	 * for(保存账单){ 保存单条账单 －保存消费记录 －保存分期记录 }<br/>
	 * 
	 * @author yuandong
	 * @param task
	 * @since JDK 1.6
	 */
	public void fetchBill(final TaobaoTask task) {
		// 这里交给线程池处理，防止下面的业务处理时间太长，导致超时。
		// 超时会导致魔蝎数据进行重试，会收到重复的回调请求
		
		
		taskExecutor.execute(
				new Runnable() {
                    @Override
                    public void run() {
            			try {
            				//查询用户的基本信息
            				saveUserInfo(task);
            				//保存收货地址
            				saveDeliverAddress(task);
            				//保存最近订单的收货地址
            				saveRecentAddress(task);
            				//保存订单和商品
            				saveTradeDetails(task);

            			} catch (Exception e) {
            				LOGGER.error("fetchBill failed. account:{}", task.getAccount(), e);
            			}
            		}
                }
				
				);
		
	}
	
	private void saveUserInfo(TaobaoTask task){
		try{
			UserInfoEntity userInfoEntity = loaduserInfoByCallApi(task.getUserId(),task.getTaskId());
			UserInfoEntity oldUserInfo = userInfoRepository.getUserInfo(task.getUserId(),task.getMappingId());
			if(oldUserInfo==null){
				userInfoRepository.saveUserInfo(userInfoEntity);
			}else{
				userInfoEntity.setId(oldUserInfo.getId());
				userInfoEntity.setCreateTime(oldUserInfo.getCreateTime());
				userInfoRepository.updateUserInfo(userInfoEntity);
			}
		}catch(Exception e){
			LOGGER.error("save taobao userinfo error",e);
		}
	}
	
	private void saveDeliverAddress(TaobaoTask task){
		try{
			taobaoDeliverAddressRepository.deleteDeliverAddress(task.getUserId(),task.getMappingId());
			loadDeliverAddressByCallApi(task.getUserId(),task.getTaskId());
		}catch(Exception e){
			LOGGER.error("saveDeliverAddress error",e);
		}
	}
	
	
	private UserInfoEntity loaduserInfoByCallApi(String userId,String taskId) throws IOException {
		TaobaoUserInfo taobaoUserInfo = taobaoClient.getUserInfo(taskId);
		if(taobaoUserInfo!=null){
			UserInfoEntity basicEntity = new UserInfoEntity();
			BeanUtils.copyProperties(taobaoUserInfo, basicEntity);
			basicEntity.setUserId(userId);
			return basicEntity;
		}
		return null;
	}
	
	
	private void loadDeliverAddressByCallApi(String userId,String taskId) throws Exception {
		List<DeliverAddress> deliverAddressList = taobaoClient.getDeliverAddress(taskId);
		if(deliverAddressList!=null&&!deliverAddressList.isEmpty()){
			for(DeliverAddress deliverAddress:deliverAddressList){
				DeliverAddressEntity basicEntity = new DeliverAddressEntity();
				BeanUtils.copyProperties(deliverAddress, basicEntity);
				basicEntity.setUserId(userId);
				taobaoDeliverAddressRepository.saveDeliverAddress(basicEntity);
			}
		}
	}
	
	
	private void saveRecentAddress(TaobaoTask task){
		try{
			List<RecentDeliverAddress> deliverAddressList = taobaoClient.getRecentAddress(task.getTaskId());
			if(deliverAddressList!=null&&!deliverAddressList.isEmpty()){
				for(RecentDeliverAddress recentDeliverAddress:deliverAddressList){
					RecentAddressEntity basicEntity = new RecentAddressEntity();
					BeanUtils.copyProperties(recentDeliverAddress, basicEntity);
					basicEntity.setUserId(task.getUserId());
					basicEntity.setMappingId(task.getMappingId());
					RecentAddressEntity isExist = recentAddressRepository.getRecentAddress(task.getUserId(), task.getMappingId(), recentDeliverAddress.getTradeId());
					if(isExist==null){
						recentAddressRepository.saveRecentAddress(basicEntity);
					}else{
						basicEntity.setId(isExist.getId());
						basicEntity.setCreateTime(isExist.getCreateTime());
						recentAddressRepository.updateRecentAddress(basicEntity);
					}
				}
			}
		}catch(Exception e){
			LOGGER.error("saveRecentAddress error",e);
		}
	}
	
	private void saveTradeDetails(TaobaoTask task){
		int page=1;
		int pageSize=200;
		try{
			
			do {
				TradeDetailsRes tradeDetailsRes = taobaoClient.getTradeDetailsRes(task.getTaskId(), page, pageSize);
				if (tradeDetailsRes != null && tradeDetailsRes.getSize() > 0) {
					pageSize = tradeDetailsRes.getSize();
					List<TradeDetails> tradeDetailsList = tradeDetailsRes.getTradedetails();
					for (TradeDetails tradeDetails : tradeDetailsList) {
						TradeDetailEntity tradeDetailEntity = new TradeDetailEntity();
						BeanUtils.copyProperties(tradeDetails, tradeDetailEntity);
						tradeDetailEntity.setUserId(task.getUserId());
						
						//保存消费记录
						TradeDetailEntity isExist = taobaoTradeInfoRepository.getTradeDetailEntity(task.getUserId(), task.getMappingId(), tradeDetails.getTradeId());
						if(isExist==null){
							taobaoTradeInfoRepository.saveTradeDetail(tradeDetailEntity);
						}else{
							tradeDetailEntity.setId(isExist.getId());
							tradeDetailEntity.setCreateTime(isExist.getCreateTime());
							taobaoTradeInfoRepository.updateTradeDetail(tradeDetailEntity);
						}
					  
						//保存商品信息
						List<TaobaoSubOrder> subOrders = tradeDetails.getSubOrders();
						if(subOrders!=null&&!subOrders.isEmpty()){
							taobaoSuborderRepository.deleteSubOrder(task.getUserId(), tradeDetails.getMappingId(), tradeDetails.getTradeId());
							for(TaobaoSubOrder taobaoSubOrder:subOrders){
								SubOrderEntity subOrderEntity = new SubOrderEntity();
								BeanUtils.copyProperties(taobaoSubOrder, subOrderEntity);
								subOrderEntity.setUserId(task.getUserId());
								taobaoSuborderRepository.saveSubOrder(subOrderEntity);
							}
						}
						
					}
				} else {
					pageSize = 0;
				}
				
				page++;
			} while (pageSize == 200);
		}catch(Exception e){
			LOGGER.error("saveTradeDetails error",e);
		}
	}
	

	
}
